package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import commentDao.CommentDAO;
import commentDao.CommentEntity;
import commentDao.MySqlCommentDao;
import newsDao.MySqlNewsDao;
import newsDao.NewsDAO;
import newsDao.NewsEntity;
import page.Page;
import topicDao.MySqlTopicDao;
import topicDao.TopicEntity;
import usersDao.MySqlUsersDao;
import usersDao.UsersEntity;

public class IndexServlet extends HttpServlet {

	public IndexServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("utf-8");
		String uname = request.getParameter("uname");
		String upwd = request.getParameter("upwd");
		MySqlUsersDao usersdao = new MySqlUsersDao();
		UsersEntity user = usersdao.login(uname, upwd);
		if (user == null) {
			out.print("<script>alert('用户名或密码输入错误！');history.back();</script>");
			return;
		}
		HttpSession s = request.getSession();
		s.setAttribute("USER", user);
		response.sendRedirect("admin.do");
		out.flush();
		out.close();
	}

	public void loginOut(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		UsersEntity user = (UsersEntity) session.getAttribute("USER");
		if (user != null) {
			session.removeAttribute("USER");
			response.sendRedirect("index.jsp");
		}
	}

	public void admin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int pageNo = 1;
		MySqlNewsDao newsdao = new MySqlNewsDao();
		try {
			pageNo = Integer.parseInt(request.getParameter("pageNo"));
		} catch (Exception e) {
		}

		Page<NewsEntity> page = newsdao.query(pageNo);
		request.setAttribute("page", page);
		request.getRequestDispatcher("adminPage.jsp").forward(request, response);
	}

	public void addNewsPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		MySqlTopicDao topic = new MySqlTopicDao();
		List<TopicEntity> list = topic.findAll();
		request.setAttribute("topics", list);
		request.getRequestDispatcher("addnews.jsp").forward(request, response);
	}

	public void addNews(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PrintWriter out = response.getWriter();
		ServletContext application = this.getServletContext();
		DiskFileItemFactory dfi = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(dfi);
		upload.setHeaderEncoding("UTF-8");
		List<FileItem> list = upload.parseRequest(request);
		NewsEntity n = new NewsEntity();
		for (FileItem f : list) {
			if (f.isFormField()) {
				if (f.getFieldName().equalsIgnoreCase("ntid")) {
					int ntid = Integer.parseInt(f.getString("UTF-8"));
					n.setNtid(ntid);
				}
				if (f.getFieldName().equalsIgnoreCase("ntitle")) {
					String ntitle = f.getString("UTF-8");
					if (ntitle == null || "".equals(ntitle.trim())) {
						out.print("<script>alert('标题不能为空！');history.back();</script>");
						return;
					}
					n.setNtitle(ntitle);
				}
				if (f.getFieldName().equalsIgnoreCase("nauthor")) {
					String nauthor = f.getString("UTF-8");
					if (nauthor == null || "".equals(nauthor.trim())) {
						out.print("<script>alert('作者不能为空！');history.back();</script>");
						return;
					}
					n.setNauthor(nauthor);
				}
				if (f.getFieldName().equalsIgnoreCase("nsummary")) {
					String nsummary = f.getString("UTF-8");
					if (nsummary == null || "".equals(nsummary.trim())) {
						out.print("<script>alert('摘要不能为空');history.back();</script>");
						return;
					}
					n.setNsummary(nsummary);
				}
				if (f.getFieldName().equalsIgnoreCase("ncontent")) {
					String ncontent = f.getString("UTF-8");
					if (ncontent == null || "".equals(ncontent.trim())) {
						out.print("<script>alert('内容不能为空！');history.back();</script>");
						return;
					}
					n.setNcontent(ncontent);
				}
			} else {
				String oldName = f.getName();
				if (oldName == null || oldName.trim().equals("")) {
					continue;
				}
				String filePath = application.getRealPath("images");
				String houzhui = oldName.substring(oldName.lastIndexOf('.'));
				if (!(houzhui.equals(".png") || houzhui.equals(".bmp") || houzhui.equals(".gif")
						|| houzhui.equals(".jpg"))) {
					out.print("<script>alert('你上传的不是图片文件！');history.back();</script>");
					return;
				}
				String newFileName = UUID.randomUUID() + houzhui;
				f.write(new java.io.File(filePath, newFileName));
				n.setNpicPath("images/" + newFileName);
			}
		}
		java.util.Date d = new java.util.Date();
		Timestamp date = new Timestamp(d.getTime());
		n.setNcreateDate(date);
		n.setNmodifyDate(date);
		MySqlNewsDao newdao = new MySqlNewsDao();
		int r = newdao.add(n);
		if (r > 0) {
			out.print("<script>alert('增加新闻成功');window.location.href='addnews.jsp';</script>");

		} else {
			out.print("<script>alert('增加新闻失败');history.back();</script>");
		}
	}

	public void updatePage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		long nid = 0;
		try {
			nid = Long.parseLong(request.getParameter("nid"));
		} catch (Exception e) {
		}
		MySqlCommentDao commdao = new MySqlCommentDao();
		List<CommentEntity> list2 = commdao.findComments(nid);
		MySqlNewsDao nd = new MySqlNewsDao();
		NewsEntity n = nd.find(nid);
		if (n == null) {
			out.print("<script>alert('没有此新闻！');history.back();</script>");
			return;
		}
		MySqlTopicDao tdao = new MySqlTopicDao();
		List<TopicEntity> topics = tdao.findAll();
		request.setAttribute("news", n);
		request.setAttribute("topics", topics);
		request.setAttribute("comments", list2);

		request.getRequestDispatcher("updatenews.jsp").forward(request, response);
	}

	public void update(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PrintWriter out = response.getWriter();
		ServletContext application = this.getServletContext();
		request.setCharacterEncoding("UTF-8");
		NewsEntity n = new NewsEntity();
		Date d = new Date();
		Timestamp date = new Timestamp(d.getTime());
		n.setNmodifyDate(date);
		DiskFileItemFactory df = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(df);
		upload.setHeaderEncoding("UTF-8");
		List<FileItem> list = upload.parseRequest(request);
		for (FileItem f : list) {
			if (f.isFormField()) {
				if (f.getFieldName().equalsIgnoreCase("nid")) {
					n.setNid(Integer.parseInt(f.getString("UTF-8")));
				}
				if (f.getFieldName().equalsIgnoreCase("ntid")) {
					n.setNtid(Integer.parseInt(f.getString("UTF-8")));
				}
				if (f.getFieldName().equalsIgnoreCase("ntitle")) {
					n.setNtitle(f.getString("UTF-8"));
				}
				if (f.getFieldName().equalsIgnoreCase("nauthor")) {
					n.setNauthor(f.getString("UTF-8"));
				}
				if (f.getFieldName().equalsIgnoreCase("nsummary")) {
					n.setNsummary(f.getString("UTF-8"));
				}
				if (f.getFieldName().equalsIgnoreCase("ncontent")) {
					n.setNcontent(f.getString("UTF-8"));
				}
			} else {
				String oldName = f.getName();
				if (oldName == null || oldName.trim().equals("")) {
					continue;
				}
				String filePath = application.getRealPath("images");
				String houzhui = oldName.substring(oldName.lastIndexOf('.'));
				if (!(houzhui.equals(".png") || houzhui.equals(".bmp") || houzhui.equals(".gif")
						|| houzhui.equals(".jpg"))) {
					out.print("<script>alert('你上传的不是图片文件！');history.back();</script>");
					return;
				}
				String newFileName = UUID.randomUUID() + houzhui;
				f.write(new java.io.File(filePath, newFileName));
				n.setNpicPath("images/" + newFileName);
			}
		}
		MySqlNewsDao newdao = new MySqlNewsDao();
		int result = newdao.update(n);
		if (result > 0) {
			out.print("<script>alert('新闻修改成功！');window.location.href='admin.do';</script>");
		} else {
			out.print("<script>alert('新闻修改失败！');history.back();</script>");
		}
	}

	public void deleNews(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		long nid = Long.parseLong(request.getParameter("nid"));
		MySqlNewsDao newsDao = new MySqlNewsDao();
		int r = newsDao.del(nid);
		if (r > 0) {
			out.print("<script>alert('删除成功！');location.replace('admin.do');</script>");
		}
	}

	public void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		MySqlNewsDao news = new MySqlNewsDao();
		List<NewsEntity> country = news.findTop(1);
		List<NewsEntity> entertainment = news.findTop(5);
		List<NewsEntity> linternational = news.findTop(2);
		int pageNo = 1;
		MySqlNewsDao newsdao = new MySqlNewsDao();
		try {
			pageNo = Integer.parseInt(request.getParameter("pageNo"));
		} catch (Exception e) {
		}
		Integer tid = null;
		try {
			tid = Integer.parseInt(request.getParameter("tid"));
		} catch (Exception e) {
		}
		Page<NewsEntity> page = newsdao.find(pageNo, tid);
		request.setAttribute("page", page);
		request.setAttribute("tid", tid);
		MySqlTopicDao tpdao = new MySqlTopicDao();
		List<TopicEntity> topic = tpdao.findAll();
		request.setAttribute("country", country);
		request.setAttribute("entertainment", entertainment);
		request.setAttribute("linternational", linternational);
		request.setAttribute("topiclist", topic);
		request.getRequestDispatcher("main.jsp").forward(request, response);
	}

	public void deleTopic(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		int t = Integer.parseInt(request.getParameter("tid"));
		MySqlTopicDao td = new MySqlTopicDao();
		int a = td.del(t);
		if (a > 0) {
			out.print("<script>alert('删除主题成功！');location.replace('Topic');</script>");
			return;
		}
		out.print("<script>alert('删除主题失败！');history.back();</script>");
	}

	public void newsRead(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		NewsDAO ndao = new MySqlNewsDao();
		NewsEntity news = ndao.find(Long.parseLong(request.getParameter("nid")));
		CommentDAO comm = new MySqlCommentDao();
		List<CommentEntity> listc = comm.findComments(Long.parseLong(request.getParameter("nid")));
		List<NewsEntity> country = ndao.findTop(1);
		List<NewsEntity> entertainment = ndao.findTop(5);
		List<NewsEntity> linternational = ndao.findTop(2);
		request.setAttribute("country", country);
		request.setAttribute("entertainment", entertainment);
		request.setAttribute("linternational", linternational);
		request.setAttribute("news", news);
		request.setAttribute("commentlist", listc);
		request.getRequestDispatcher("news_read.jsp").forward(request, response);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		// PrintWriter out = response.getWriter();
		String path = request.getServletPath();
		path = path.substring(1, path.length() - 3);
		try {
			if (path.equals("service") || path.equals("doGet") || path.equals("doPost")) {
				response.sendError(500, "禁止的操作");
				return;
			}
			Method m = this.getClass().getDeclaredMethod(path, HttpServletRequest.class, HttpServletResponse.class);
			m.invoke(this, request, response);
			return;
			// 一步杀掉所有的if else
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			response.sendError(404, "没有对应的操作");
		}
		// out.flush();
		// out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);

	}

	public void init() throws ServletException {
	}

}
